package net.crawler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.ResultSet;
import net.bd.MySQL;
import net.bd.PostgreSQL;

public class Crawler {
	
	/**
	 * 
	 */
	public static void run() {
		
		try {
			
			ProcessBuilder pb = new ProcessBuilder("java", "-jar", "ifrit.jar");
	    	pb.redirectErrorStream(true);
	    	pb.directory(new File("D:\\UFRGS\\trabalhos\\MeuTCC\\src\\ProjectIfrit"));
	    	
	    	Process p = pb.start();
			listen(p.getInputStream(), "output: ",p);  
	        listen(p.getErrorStream(), "ERROR: ",p);
	        
	        try {
				p.waitFor();
				System.out.println("ending crawler");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 
	 * @param url
	 */
	public static void cadastraUrl(String url){
		
		File to = new File("src/ProjectIfrit/input file.txt");
		
		try {
			to.delete();
			to.createNewFile();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try {
			FileWriter out = new FileWriter(to);
			PrintWriter printerOut = new PrintWriter(to);
			
			printerOut.println(url);
			printerOut.flush();
			
			out.close();
			printerOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
		
	/**
	 * 
	 * @param stream
	 * @param prefix
	 * @param p
	 */
	private static void listen(InputStream stream, final String prefix, final Process p) {  
	    final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
	    
	    new Thread(new Runnable() {  
	        public void run() {  
	            String line;  
	            try {  
	                while ((line = reader.readLine()) != null) {  
	                    System.out.println(prefix + line);
	                	if (line.contentEquals("Edite o arquivo de entrada antes de responder.")){
	                		BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
	                		w.write("N");
	                		w.flush();
	                		System.out.println("input");
	                		w.close();
	                		p.destroy();
	                	}
	                }
	            } catch (IOException x) {  
	                x.printStackTrace();  
	            }  
	        }  
	    }).start();  
	}
	
	/**
	 * 
	 */
	public static void importFormToWFSim(String url){
		 
		ResultSet result, result2;
		int id, wff_id;
		String type;
		String label;
		String urlTarget = url;
		
		if (urlTarget.subSequence(urlTarget.length()-1,urlTarget.length()).toString().contains("/")) {
			urlTarget = (String) urlTarget.subSequence(0, urlTarget.length()-1);
		}
		
		try {
			
			MySQL.inicializaBD();
			id = MySQL.getCurrentFormId();
			PostgreSQL.inicializaBD();
			result = PostgreSQL.getFormToElement(urlTarget);
			
			System.out.println("importing form " + urlTarget);
			
			while(result.next()) {
				
				id++;
				wff_id = result.getInt("id");
				url = result.getString("url");
				type = result.getString("type");
				label = result.getString("label");
				
				MySQL.insertFormElement(id, url, type, label);
				
				result2 = PostgreSQL.getFormElementValues(wff_id);
				
				while(result2.next()) {
					MySQL.insertFormElementValues(id, result2.getString("value"));
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}
